package program.utils;

import program.domain.Memory;
import program.domain.PCB;
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;

/**
 * @program: OSAlgorithms
 * @description: 文件数据处理工具类
 * @author: W
 * @create: 2021-10-29 19:19
 **/
public class FileUtil {
    /**
     * 存储数据信息
     */
    public static String[] data;

    /**
     * 读取存放数据的文件
     */
    public static void readFile(String fileName) {
        File directory = new File("");
        String filePath = null;
        String[] mData = new String[100];
        try {
            filePath = directory.getCanonicalPath() + "\\src\\main\\resources\\"+fileName;
        } catch (IOException e) {
            e.printStackTrace();
        }

        File dataFile = new File(filePath);
        if (!dataFile.exists()) {
            System.out.println("未找到数据文件");
        }

        try {
            BufferedReader reader = new BufferedReader(new FileReader(dataFile));
            String str;
            int num = 0;
            while ((str = reader.readLine()) != null) {
                mData[num++] = str;
            }
            reader.close();

            data = new String[num];
            for (int i=0;i<num;i++){
                data[i] = mData[i];
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取进程信息
     * @return 存放所有进程的List
     */
    public static ArrayList<PCB> getProcessData(String fileName) {
        readFile(fileName);
        ArrayList<PCB> processes = new ArrayList<>();
        for (int i=0;i<data.length;i++){
            //分割字符串 0-PID，1-到达时刻，2-cpu处理时间
            String[] str = data[i].split(",");
            String pid = str[0];
            Integer arriveTime = Integer.valueOf(str[1]);
            Integer cpuTime = Integer.valueOf(str[2]);
            PCB pcb = new PCB(pid,arriveTime,cpuTime,"创建");
            pcb.setNeedTime(cpuTime);
            processes.add(pcb);
        }
        Collections.sort(processes);
        return processes;
    }

    /**
     * 获取空闲内存数据
     * @param fileName
     * @return 存放所有空闲区的List
     */
    public static ArrayList<Memory> getMemoryData(String fileName){
        readFile(fileName);
        ArrayList<Memory> memories = new ArrayList<>();
        for (int i=0;i<data.length;i++){
            //分割字符串 0-起始地址 1-大小
            String[] str = data[i].split(",");
            Integer start = Integer.valueOf(str[0]);
            Integer length = Integer.valueOf(str[1]);
            Memory memory = new Memory(start,length,null);
            memories.add(memory);
        }
        return memories;
    }
}
